package com.leyou.auth.service.impl;

import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.exception.LyException;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserAuthServiceImpl implements UserAuthService {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserClient userClient;

    public UserAuthServiceImpl(JwtUtils jwtUtils, UserClient userClient) {
        this.jwtUtils = jwtUtils;
        this.userClient = userClient;
    }

    @Override
    public void login(HttpServletResponse response, String username, String password) {
        UserDTO userDTO = null;
        try {
            userDTO=userClient.queryUserByusernameAndPassword(username, password);
        } catch (FeignException e) {
            new LyException(e.status(),e.getMessage());
        }

        UserDetail userDetail = UserDetail.of(userDTO.getId(), userDTO.getUsername());
        String jwt = jwtUtils.createJwt(userDetail);
        Cookie cookie = new Cookie("LY_TOKEN",jwt);
        cookie.setDomain("leyou.com");
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        response.addCookie(cookie);
    }


}
